package info.liujiachen.security.test.service;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class JwtUserDetailsService implements UserDetailsService {

    private PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();

    private String salt = "123abc";

    private List<Map<String, String>> users = Collections.emptyList();

    public JwtUserDetailsService() {
        createUser("user", "123456");
    }

    public void createUser(String username, String password) {
        /**
         * @todo 保存用户名和加密后密码到数据库
         */
        users = new ArrayList<>();
        Map<String, String> user = new HashMap<>();
        user.put("username", "user");
        user.put("password", "123456");
        user.put("role", "USER");
        users.add(user);
    }

    public Map<String, String> findUser(String username) {
        /**
         * @todo 使用用户名到数据库查找
         */
        Map<String, String> findUser = null;
        for (Map<String, String> user : users) {
            if (StringUtils.equals(username, user.get("username"))) {
                findUser = new HashMap<>();
                findUser.put("username", user.get("username"));
                findUser.put("password", user.get("password"));
                findUser.put("role", user.get("user"));
            }
        }
        return findUser;
    }

    public void deleteUserLoginInfo(String username) {
        /**
         * @todo 清除数据库或者缓存中登录salt
         */
        for (Map<String, String> user : users) {
            if (StringUtils.equals(username, user.get("username"))) {
                users.remove(user);
            }
        }
    }

    public UserDetails getUserLoginInfo(String username) {
//        String salt = "123456ef";
        /**
         * @todo 从数据库或者缓存中取出jwt token生成时用的salt
         * salt = redisTemplate.opsForValue().get("token:"+username);
         */
        UserDetails user = loadUserByUsername(username);
        //将salt放到password字段返回
        return User.builder().username(user.getUsername()).password(salt).authorities(user.getAuthorities()).build();
    }

    public String saveUserLoginInfo(UserDetails user) {
//        String salt = "123456ef"; //BCrypt.gensalt();  正式开发时可以调用该方法实时生成加密的salt
        /**
         * @todo 将salt保存到数据库或者缓存中
         * redisTemplate.opsForValue().set("token:"+username, salt, 3600, TimeUnit.SECONDS);
         */
        Algorithm algorithm = Algorithm.HMAC256(salt);
        Date date = new Date(System.currentTimeMillis() + 60 * 60 * 1000);  //设置1小时后过期
        return JWT.create()
                .withSubject(user.getUsername())
                .withExpiresAt(date)
                .withIssuedAt(new Date())
                .sign(algorithm);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Map<String, String> user = findUser(username);
        if (user == null) {
            System.out.println(String.format("User not found by username '%s'.", username));
            throw new UsernameNotFoundException(String.format("User not found by username '%s'.", username));
        } else {
            List<JwtGrantedAuthority> list = new ArrayList<>();
            list.add(new JwtGrantedAuthority("user"));
            return User.builder().username(username).password(encoder.encode(user.get("password"))).authorities(list).build();
        }
    }

}
